window.onload = function () {
    getData();

    async function getData() {
        let res = await pAjax({
            url: "./shop.php",
        });
        res = JSON.parse(res);
        console.log(res);
        // ！需要把数据库中所有的商品列表(res),存在 本地存储中
        localStorage.setItem('dataList', JSON.stringify(res))
    }

    let res = location.search.match(/\?id=(\d+)/); //!!!捕获网页参数,以只拿到对应goodsid的数据来进行渲染。对应了前面写的 location.href = `./shop/shop.html?id=${index+1}。
    if (!res) {
        // location.href = "../page/list.html";
        console.log(0);
        return;
    }
    let id = res[1]; //拿到索引为1的值：1/2/3
    let spinlist = document.querySelector("#spinlist");
    let showtu = document.querySelector("#show");
    let yi = document.querySelector("#yi");
    let er = document.querySelector("#er");
    let san = document.querySelector("#san");
    let si = document.querySelector("#si");
    let wu = document.querySelector("#wu");
    let liu = document.querySelector("#xinghao1");
    let qi = document.querySelector("#xinghao2");
    let ba = document.querySelector("#ba");
    let jiu = document.querySelector("#jiu");
    let ten = document.querySelector("#ten");
    let enlarge = document.querySelector(".enlarge");

    let data = JSON.parse(localStorage.getItem("dataList"));
    console.log(data);
    let details = data.filter((item) => {
        return item.goods_id == id;
    })[0]; //!过滤出对应id的数据
    console.log(details); //注意filter返回的是一个数组，且是只有一个数据的，所以只能拿索引为0的。
    if (!details) { //这个判断没看懂
        // 发送一个ajax请求
        let p = pAjax({
            url: "./detail.php",
            data: {
                id: id,
            },
        });
        p.then((res) => {
            res = JSON.parse(res);
            render(res.detail);
        });
    } else {
        render(details); //details是对应id的全部数据。对应37行的details
    }

    function render(data) { //!！！
        console.log(500);
        yi.innerText = data.yi;
        er.innerText = data.er;
        san.innerText = data.san;
        si.innerText = data.si;
        wu.innerText = data.wu;
        liu.innerText = data.liu;
        qi.innerText = data.qi;
        ba.src = data.ba;
        jiu.src = data.jiu;
        str1 = `<img id="ten" src="${data.ba}" alt="" class="img1">
                    <div class="mask"></div>`
        showtu.innerHTML = str1;
        str2 =
            `<p class="active">
                        <img id="ba" src="${data.ba}" alt="" class="img2"
                            midelImg="${data.ba}">
                        <!-- 要给个属性值 -->
                    </p>
                    <p>
                        <img id="jiu" src="${data.jiu}" alt="" class="img2"
                            midelImg="${data.jiu}">
                    </p>`
        spinlist.innerHTML = str2;
        enlarge.style.backgroundImage = `url(${data.ba})`;
        console.log(100);
        // img.src = data.goods_big_logo;
        // title.innerText = data.goods_name;
        // price.innerText = data.goods_price;
        // introduce.innerHTML = data.goods_introduce;
    }



    // 点击加入购物车功能
    // 判断是否有登录
    // 没有登录的时候
    // 登录 把用户名存在cookie
    // key: login 值： 用户名
    let addCar = document.querySelector("#addCar");
    addCar.onclick = function (e) {
        e = e || window.event;
        e.returnValue = false;
        // console.log(1);
        let login = getCookie("login");
        if (!login) {
            // !!!需要把当前这个页面url(当前的shop页面)存储 本地存储中
            localStorage.setItem('url', location.href);
            location.href = '../login/login.html';
            return
        }
        // 发送添加购物车的ajax请求
        //负责传参，和判断跳转到购物车页面
        let p = pAjax({
            url: "../api/addCarData.php",
            type: "post",
            data: {
                username: login,
                goods_id: id,
            },
        });
        p.then(res => {
            console.log(7);
            res = JSON.parse(res);
            console.log(res);
            let r = res.code ? confirm('添加成功是否要到购物车查看') : alert('添加失败');
            location.href = r ? '../car/cart2.html' : '';
        })
    };


    //放大镜
    class Enlarge {
        constructor(ele) { //静态书写
            this.ele = document.querySelector(ele);
            this.init();
        }
        init() { //动态属性
            this.show = this.ele.querySelector(".show");
            this.mask = this.show.querySelector(".mask");
            this.showImg = this.show.querySelector(".img1");

            this.enlarge = this.ele.querySelector(".enlarge");
            this.p = this.ele.querySelectorAll(".list p");

            // 如果不适用箭头函数的时候 可以用一个变量把这个函数中的this存起来
            // let _this = this;

            // 给show盒子绑定一个鼠标移入事件
            this.show.onmouseover = () => {
                // _this.mask.style.display = 'block';
                this.mask.style.display = "block";
                this.enlarge.style.display = "block";
                // this.enlarge.style.backgroundSize = "cover"
                this.enlarge.style.backgroundPosition = "center"
                this.setStyle();
            };

            this.show.onmouseout = () => {
                this.mask.style.display = "none";
                this.enlarge.style.display = "none";
                this.show.style.border = "none";
            };

            // 在show盒子中移动的时候 mask跟随光标移动
            this.show.onmousemove = (e) => {
                var e = e || window.event;
                this.maskMove(e);
                this.enlargerMove();
                this.show.style.border = "1px solid rgb(0, 162, 255)";
            };

            this.p.forEach((item) => {
                item.onmousemove = () => {
                    this.changeImg(item);
                }
            })
        }
        setStyle() { // 求enlarge盒子背景图大小,好像和css有关系。

            // show盒子大小
            // mask盒子大小

            // '750px 1000px'
            let res = this.getStyle(this.enlarge, "backgroundSize");
            let bgW = parseInt(res.split(" ")[0]);
            let bgH = parseInt(res.split(" ")[1]);

            let showW = this.show.offsetWidth;
            let showH = this.show.offsetHeight;

            let maskW = this.mask.offsetWidth;
            let maskH = this.mask.offsetHeight;

            let w = (bgW * maskW) / showW;
            let h = (bgH * maskH) / showH;

            // this.enlarge.style.width = "480px";
            // this.enlarge.style.height = "480px";
            this.enlarge.style.width = w + "px";
            this.enlarge.style.height = h + "px";
        }

        getStyle(ele, attr) {
            return window.getComputedStyle(ele)[attr];
        }

        maskMove(e) { //只是判断光标的。
            let boxX = this.ele.offsetLeft;
            let boxY = this.ele.offsetTop;

            this.x = e.pageX - boxX - this.mask.offsetWidth / 2;
            this.y = e.pageY - boxY - this.mask.offsetHeight / 2;

            if (this.x <= 0) {
                this.x = 0;
            }
            if (this.y <= 0) {
                this.y = 0;
            }
            if (
                this.x >=
                this.show.offsetWidth - this.mask.offsetWidth
            ) {
                this.x = this.show.offsetWidth - this.mask.offsetWidth;
            }
            if (
                this.y >=
                this.show.offsetHeight - this.mask.offsetHeight
            ) {
                this.y =
                    this.show.offsetHeight - this.mask.offsetHeight;
            }

            this.mask.style.left = this.x + "px";
            this.mask.style.top = this.y + "px";
        }

        enlargerMove() { //！设置放大图的位置
            let res = this.getStyle(this.enlarge, "backgroundSize");
            let bgW = parseInt(res.split(" ")[0]);
            let bgH = parseInt(res.split(" ")[1]);

            let showW = this.show.offsetWidth;
            let showH = this.show.offsetHeight;

            let bgX = (bgW * this.x) / showW;
            let bgY = (bgH * this.y) / showH;
            this.enlarge.style.backgroundPosition = `${-bgX}px ${-bgY}px`
        }

        changeImg(ele) {
            console.log(100);
            // ele 当前点击这个元素
            for (let i = 0; i < this.p.length; i++) {
                this.p[i].classList.remove('active');
            }
            ele.classList.add('active');

            // 获取当前点击元素下面的img
            let img = ele.querySelector('.img2');
            let midelImg = img.getAttribute('midelImg');
            // let bigImg = img.getAttribute('bigImg');

            this.showImg.src = midelImg;
            // let tu = ba.getAttribute;
            // console.log(tu);
            this.enlarge.style.backgroundImage = `url(${midelImg})`;
            console.log(300);
        }
    }
    new Enlarge(".fdjbox");


    // 商品数量增减
    let num = document.querySelector("#numinput");
    let reduce = document.querySelector(".button1");
    let add = document.querySelector(".button2");
    reduce.onclick = () => {
        num.value--;
        if (num.value <= 1) {
            num.value = 1;
        }
    }
    add.onclick = () => {
        num.value++;
    }
};